using Common.Communal;
using ERP.Domain.Scheduling;
using MediatR;
using Scheduling.Api.Read.Application.Command.CalendarCommand;
using SqlSugar;

namespace Scheduling.Api.Read.Application.CommandHandlers.CalendarHandler
{
    public class CalendarMonthQueryCommandHandler : IRequestHandler<CalendarMonthQueryCommand, ApiResult<List<Calendar>>>
    {
        public CalendarMonthQueryCommandHandler(ISqlSugarClient sqlSugar)
        {
            SqlSugar = sqlSugar;
        }

        public ISqlSugarClient SqlSugar { get; }

        public Task<ApiResult<List<Calendar>>> Handle(CalendarMonthQueryCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<Calendar>> result = new ApiResult<List<Calendar>>();

            if (request.Year <= 0 || request.Month <= 0 || request.Month > 12)
            {
                result.Code = EnumCode.Fail;
                result.Message = "年月参数不合法";
                return Task.FromResult(result);
            }

            var firstDay = new DateTime(request.Year, request.Month, 1);
            var nextMonth = firstDay.AddMonths(1);

            // 基础查询：本月范围内未删除记录
            var query = SqlSugar.Queryable<Calendar>()
                .Where(x => x.IsDelete == false)
                .Where(x => x.CalendarDate >= firstDay && x.CalendarDate < nextMonth);

            // 条件筛选
            if (request.IsWorkDay.HasValue)
                query = query.Where(x => x.IsWorkDay == request.IsWorkDay.Value);
            if (request.IsUrgentWorkday.HasValue)
                query = query.Where(x => x.IsUrgentWorkday == request.IsUrgentWorkday.Value);
            if (!string.IsNullOrWhiteSpace(request.HoildayType))
                query = query.Where(x => x.HoildayType == request.HoildayType);
            if (!string.IsNullOrWhiteSpace(request.ReasonKeyword))
                query = query.Where(x => x.UrgentReason.Contains(request.ReasonKeyword));

            var list = query.OrderBy(x => x.CalendarDate).ToList();

            result.Code = EnumCode.Ok;
            result.Message = "日历按月查询成功";
            result.Data = list;
            return Task.FromResult(result);
        }
    }
}


